package com.binance.graceful.shutdown.config;

import org.eclipse.jetty.server.Server;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.embedded.jetty.JettyEmbeddedServletContainerFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.binance.graceful.shutdown.core.GracefulShutdownJetty;

import lombok.extern.log4j.Log4j2;

/**
 * Created by robin.wu on 2018/10/29.
 */
@Log4j2
@Configuration
@EnableConfigurationProperties(ShutdownProperties.class)
@ConditionalOnClass(value = Server.class)
@ConditionalOnProperty(prefix = "jetty.graceful.shutdown", name = "enabled", havingValue = "true", matchIfMissing = false)
public class GracefulShutdownJettyAutoConfiguration {

    @Bean
    @ConditionalOnClass(value = org.eclipse.jetty.server.Server.class)
    public GracefulShutdownJetty jettyGracefulShutdown(ShutdownProperties shutdownProperties) {
        return new GracefulShutdownJetty(shutdownProperties.getWaitTime());
    }

    @Bean
    @ConditionalOnClass(value = org.eclipse.jetty.server.Server.class)
    public JettyEmbeddedServletContainerFactory jettyEmbeddedServletContainerFactory(ShutdownProperties shutdownProperties) {
        JettyEmbeddedServletContainerFactory factory = new JettyEmbeddedServletContainerFactory();
        factory.addServerCustomizers(jettyGracefulShutdown(shutdownProperties));
        return factory;
    }
}
